<template>
	<jk-dialog
		v-model="showDialog"
		title="批量绑定"
		width="1000px"
		:show-content-loading="showLoading"
		append-to-body
		:confirm-btn-loading="confirmBtnLoading"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn('save')"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false" class="padding-top-10">
			<el-form-item ref="box1" class="margin-bottom-10" label="">
				<jk-divider-card title="查询条件" icon="el-icon-search">
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域">
								<el-select v-model="ruleForm.workshopId" clearable placeholder="区域" size="small" class="width-100-percent" @change="getListRequest">
									<el-option v-for="item in workshopList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="班组">
								<el-select v-model="ruleForm.groupId" clearable placeholder="班组" size="small" class="width-100-percent" @change="getListRequest">
									<el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="岗位">
								<el-select v-model="ruleForm.postId" clearable placeholder="岗位" size="small" class="width-100-percent" @change="getListRequest">
									<el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-divider-card>
			</el-form-item>
			<el-row>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="人机绑定">
						<div class="emp-machine-container" :style="{ height: `${dialogTableHeight - 40}px` }">
							<div
								v-for="(empItem, empIndex) in empList"
								:key="empIndex"
								class="emp-item"
							>
								<div class="emp-box">
									<el-button style="width: 100%;" type="default" size="small" @click="onAddMachineBtn(empIndex)">
										<span style="font-size: 14px;color: #515a6e;font-weight: 700;">{{ empItem.name }}</span>
									</el-button>
									<span style="color: #808695;font-size: 12px;white-space: nowrap;">{{ `(${empItem.empMachineList ? empItem.empMachineList.length : '0'}台)` }}</span>
								</div>
								<div class="machine-box">
									<div class="machine-box-inner">
										<div
											v-for="(machineItem, machineIndex) in empItem.empMachineList"
											:key="machineIndex"
											class="machine-item"
											style="width: calc(100% / 6);"
										>
											<el-tag
												effect="plain"
												class="width-100-percent flex-center"
												closable
												@close="onRemoveMachine(empIndex, machineIndex)"
											>{{ machineItem.machineName }}</el-tag>
										</div>
										<div class="machine-item">
											<el-tag class="el-icon-plus" @click="onAddMachineBtn(empIndex)"></el-tag>
										</div>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<select-machine-dialog
			:default-select-rows="selectedEmpMachineList"
			check-key-name="machineId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		></select-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import selectMachineDialog from './components/checkbox-machine-dialog';
    import {
        workforcemanagementEmpMachineBatchCreate,
        workforcemanagementEmpMachinePage
    } from '../../../api/schedule/empMachine';
    import { systemPostPage } from '../../../api/system/post';
    export default {
        name: 'BatchEmpMachine',
        components: { selectMachineDialog },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectedEmpMachineList: [],
                selectedEmpIdx: null,
                postList: [],
                groupList: [],
                workshopList: [],
                selectMachineDialogState: false,
                empList: [],
                scheduleList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                ruleForm: {
                    workshopId: null,
                    workshopName: '',
                    groupId: null,
                    groupName: '',
                    postId: null,
                    postName: ''
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    groupId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onAddMachineBtn(empIdx) {
                this.selectedEmpIdx = empIdx;
                this.selectedEmpMachineList = this.empList[empIdx].empMachineList || [];
                this.selectMachineDialogState = true;
            },
            onRemoveMachine(empIdx, machineIdx) {
                this.empList[empIdx].empMachineList.splice(machineIdx, 1);
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onConfirmBtnOfSelectMachineDialog(e) {
                if (e.length) {
                    this.selectMachineDialogState = false;
                    e.forEach(x => {
                        this.empList[this.selectedEmpIdx].empMachineList.push({
                            machineId: x.id,
                            machineCode: x.code,
                            machineName: x.name,
                            processId: x.processId,
                            processCode: x.processCode,
                            processName: x.processName,
                            endSpinNumber: x.spinCount,
                            startSpinNumber: 0,
                            openSpinCount: 0
                        });
                    });
                }
            },
            onSelectEmpIcon() {
                this.selectMachineDialogState = true;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.$refs['ruleForm'].validate(valid => {
                            if (valid) {
                                this.confirmBtnLoading = true;
                                const arr = this.empList.map(x => {
                                    return {
                                        id: x.id,
                                        empMachineList: x.empMachineList
                                    };
                                });
                                workforcemanagementEmpMachineBatchCreate(arr).then(res => {
                                    this.confirmBtnLoading = false;
                                    if (res.data.status === 200) {
                                        this.$emit('on-finish');
                                    }
                                });
                            } else {
                                this.$tipsBar(this, 'validator');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getListRequest() {
                return workforcemanagementEmpMachinePage(this.ruleForm).then(res => {
                    if (res.data.status === 200) {
                        this.empList = res.data.res ? res.data.res.map(x => {
                            x.empMachineList = x.empMachineList || [];
                            return x;
                        }) : [];
                    }
                });
            },
            getPostListRequest() {
                return systemPostPage({ auditState: 1, pageSize: 100 }).then(res => {
                    if (res.data.status === 200) {
                        this.postList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getPostListRequest();
                if (this.ruleForm.workshopId && this.ruleForm.groupId) this.getListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.groupList = this.$store.state.user.userGroup.groupList;
                    this.$set(this.ruleForm, 'groupId', this.$store.state.user.userGroup.defaultGroupId);
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .emp-machine-container {
        overflow: auto;
        border: solid 1px #e8eaec;
        border-radius: 6px;
        .emp-item {
            border-bottom: solid 1px #e8eaec;
            position:relative;
            .emp-box {
                width: 140px;
                height: 100%;
                position:absolute;
                //background: #2d8cf0;
                color: #fff;
                display: flex;
                justify-content: center;
                align-items: center;
                border-right: solid 1px #eee;
                padding: 0 12px;
            }
            .machine-box {
                width: 100%;
                height: 100%;
                padding-left: 140px;
                box-sizing: border-box;
                .machine-box-inner {
                    padding: 8px 4px;
                    display: flex;
                    flex-wrap: wrap;
                    .machine-item {
                        padding: 2px;
                        box-sizing: border-box;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        cursor: pointer;
                    }
                }
            }
        }
    }

</style>
